const tencentcloud = require("tencentcloud-sdk-nodejs");
const logger = require('../libs/log').logger;
var util = require('util');
var _ = require('underscore');
const { Add, Update, ExecSqlparmater, ExecGetOne, Query, Exec } = require('../db/dbhelper');
const { requestGet, requestPost } = require('../libs/common');
const { wechat,MYSQL_CONF } = require('../../server_config.json');

// 身份接口参数
let SecretId = 'AKIDYsxlbHjvrXy95lDQN5YliPq2ye3D7l9I';
let SecretKey = 'vb1B5i37xWqvlLfjdIismRr1vaz81f4C';
const FaceidClient = tencentcloud.faceid.v20180301.Client;
const clientConfig = {
    credential: {
        secretId: SecretId,
        secretKey: SecretKey,
    },
    region: "ap-shanghai",
    profile: {
        httpProfile: {
            endpoint: "faceid.tencentcloudapi.com",
        },
    },
};
// 实例化要请求产品(以faceid为例)的client对象
const client_file = new FaceidClient(clientConfig);

// 身份认证
const ImageRecognition = async function (body) {
    try {
        logger.info("-----------ImageRecognition-------------------body------", body)

        // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
        let rdata = await new Promise(function (resolve, reject) {
            client_file.ImageRecognition(body, function (err, data) {
                if (err) {
                    logger.error("-----------ImageRecognition-------------------error------", err)
                    reject(err)
                } else {
                    logger.info("-----------ImageRecognition-------------------data------", data)
                    resolve(data)
                }
            })
        })
        return rdata;
    } catch (error) {
        logger.error("-----------ImageRecognition-------------------error------", error)
        return null;
    }
}

// 人脸核身认证
const CheckIdCardInformation = async function (body) {
    try {
        logger.info("-----------CheckIdCardInformation-------------------body------", body)
        // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
        let rdata = await new Promise(function (resolve, reject) {
            client_file.CheckIdCardInformation(body, function (err, data) {
                if (err) {
                    logger.error("-----------CheckIdCardInformation-------------------error------", err)
                    reject(err)
                } else {
                    logger.info("-----------CheckIdCardInformation-------------------data------", data)
                    resolve(data)
                }
            })
        })
        return rdata;
    } catch (error) {
        logger.error("-----------CheckIdCardInformation-------------------error------", error)
        return null;
    }
}
// 身份校验
const IdCardVerification = async function (body) {
    try {
        logger.info("-----------IdCardVerification-------------------body------", body)
        // 通过client对象调用想要访问的接口，需要传入请求对象以及响应回调函数
        let rdata = await new Promise(function (resolve, reject) {
            client_file.IdCardVerification(body, function (err, data) {
                if (err) {
                    logger.error("-----------IdCardVerification-------------------error------", err)
                    reject(err)
                } else {
                    logger.info("-----------IdCardVerification-------------------data------", data)
                    resolve(data)
                }
            })
        })
        return rdata;
    } catch (error) {
        logger.error("-----------IdCardVerification-------------------error------", error)
        return null;
    }
}
// 发送订阅消息
const SendWechatMsg = async function (url, body, type) {
    try {
        let access_token_data = await getToken(type || 'wechat');
        logger.info('SendWechatMsg--access_token_data--',access_token_data,type);
        if (!access_token_data.code) {
            // 格式化请求地址
            var sendmsg_url = util.format(url, access_token_data.data);
            if (body.template_id) {
                return await requestPost(sendmsg_url, JSON.stringify(body));
            } else {
                logger.error('SendWechatMsg--发送订阅消息,未获取到template_id--');
                return {
                    errcode: 1,
                    errmsg: '发送订阅消息失败，未获取到template_id'
                }
            }
        } else {
            logger.info('SendWechatMsg--发送订阅消息失败，未获取到access_token-');
            return {
                errcode: 1,
                errmsg: '发送订阅消息失败，未获取到access_token'
            }
        }
    } catch (error) {
        logger.error('SendWechatMsg--发送订阅消息,获取access_token异常--', error);
        return {
            errcode: 1,
            errmsg: '发送订阅消息异常'
        }
    }
}
async function getToken(name) {
    try {
        let datass = MYSQL_CONF.database;
        // if(datass=='hzzdb'){
        //   return await requestGet("https://apiv2.spiderslove.com/api/wechat/getAccessToken?name="+name);
        // }
        name = name || 'redspider';
        let accessTokenJson = await ExecGetOne(`SELECT * FROM hzz_wechats where name='${name}' order BY cache_duration desc `);

        //获取当前时间 
        var currentTime = new Date().getTime();
        //判断 本地存储的 access_token 是否有效
        if (!accessTokenJson || new Date(accessTokenJson.cache_duration).getTime() < currentTime) {
            //格式化请求地址

            if (name == 'redspider') {
                var url = util.format(wechat.accessTokenUrl, 'client_credential', wechat.appid, wechat.appsecret);
            }
            if (name == 'wechat') {
                var url = util.format(wechat.accessTokenUrl, 'client_credential', wechat.appid_wechat, wechat.appsecret_wechat);
            }

            let result = await requestGet(url);
            // var result = JSON.parse(newdata);
            let expires_time = new Date(new Date().getTime() + (parseInt(result.expires_in) - 200) * 1000);
            //更新本地存储的
            await setToken(result.access_token, expires_time, name);
            //将获取后的 access_token 返回
            return {
                code: 0,
                data: result.access_token
            };
        } else {
            //将本地存储的 access_token 返回
            return {
                code: 0,
                data: accessTokenJson.access_token
            };
        }
    } catch (error) {
        logger.error('getOpenid', error);
        return {
            code: 1,
            msg: error ? error.message : '获取access_token异常'
        }
    }
}

async function setToken(access_token, cache_duration, name) {
    let sql = `SELECT * FROM hzz_wechats WHERE  name=? `;
    ExecSqlparmater(sql, [name]).then(function (data) {
        if (data.length) {
            let doc = _.extend(data[0], { access_token, access_token, id: data[0].id, updatetime: new Date(), cache_duration: cache_duration });
            Update('hzz_wechats', doc);
        } else {
            let doc = {
                name: name,
                cache_duration: cache_duration,
                access_token: access_token,
                createtime: new Date(),
                updatetime: new Date()
            };
            Add('hzz_wechats', doc);
        }
    })
}

async function queryUserList(openid) {
    try {
        let tokenData = await getToken('wechat');
        if (tokenData.code) {
            logger.info("获取用户列表--accesstoken--error:::");
            return null;
        } else {
            let acctoken = tokenData.data;
            let getUsers = async function (next_openid) {
                let url = util.format(wechat.queryuserlist_wechat, acctoken);
                logger.info("获取用户列表--next_openid:::", next_openid);
                if (next_openid) {
                    url += '&next_openid=' + next_openid;
                }
                logger.info("获取用户列表--url:::", url);
                let list = await requestGet(url);
                if (list && list.next_openid && list.next_openid != next_openid) {
                    return _.union(list.data.openid, getUsers(list.next_openid));
                } else {
                    if (list && list.data && list.data.openid) {
                        return list.data.openid;
                    } else {
                        return [];
                    }
                }
            }

            let result = await getUsers(openid);
            // logger.info("获取用户列表返回：", result, result.length);
            return result;
        }
    } catch (error) {
        logger.info("获取用户列表--error:::", error);
        return null;
    }
}
async function queryUserInfo(openid) {
    try {
        if (!openid) {
            logger.info("获取用户信息--openid--null:::");
            return null;
        }
        let tokenData = await getToken('wechat');
        if (tokenData.code) {
            logger.info("获取用户信息--accesstoken--error:::");
            return null;
        } else {
            let acctoken = tokenData.data;
            var url = util.format(wechat.queryuserinfo_wechat, acctoken, openid);
            let result = await requestGet(url);
            return result;
        }
    } catch (error) {
        logger.info("获取用户信息--error:::", error);
        return null;
    }
}

async function getUserUnionid(openid) {
    try {
        if (!openid) {
            return null;
        }
        let tokenData = await getToken('redspider');
        if (tokenData.code) {
            return null;
        } else {
            let acctoken = tokenData.data;
            var url = util.format(wechat.code2session, acctoken, openid);
            let result = await requestGet(url);
            return result && result.unionid ? result.unionid : null;
        }
    } catch (error) {
        logger.info("获取用户信息返回--error：", error);
        return null;
    }
}

async function sendIm(body){
    let url = 'http://rest-hangzhou.goeasy.io/v2/im/message';
    let result = await requestPost(url, body);
    if(result.code==200){
        logger.info('-----给推荐人发送消息----sendIm---success',result)
    }else{
        logger.info('-----给推荐人发送消息----sendIm---error',result)
    }
}

module.exports = {
    ImageRecognition,
    CheckIdCardInformation,
    IdCardVerification,
    SendWechatMsg,
    getToken,
    queryUserList,
    queryUserInfo,
    getUserUnionid,
    sendIm
};